<template>
  <a-modal
    :visible="visible"
    title="设置"
    :footer="null"
    @cancel="handleCancel"
    @update:visible="(val) => emit('update:visible', val)"
    width="800px"
    class="settings-modal"
  >
    <div class="settings-container">
      <!-- 左侧头像设置 -->
      <div class="avatar-section">
        <div class="avatar-wrapper">
          <a-avatar :size="150" :src="previewAvatar || userInfo?.avatar" />
          <div class="avatar-overlay" @click="triggerUpload">
            <camera-outlined />
            <span>更换头像</span>
          </div>
        </div>
        <input
          type="file"
          ref="fileInput"
          style="display: none"
          accept="image/*"
          @change="handleAvatarChange"
        />
        <a-button type="primary" class="upload-btn" @click="triggerUpload">
          上传新头像
        </a-button>
      </div>

      <!-- 右侧信息设置 -->
      <div class="info-section">
        <a-tabs>
          <!-- 基本信息设置 -->
          <a-tab-pane key="1" tab="基本信息">
            <a-form :model="formState" layout="vertical">
              <a-form-item label="昵称">
                <a-input
                  v-model:value="formState.nickname"
                  placeholder="请输入昵称"
                />
              </a-form-item>
              <a-form-item label="年龄">
                <a-input-number
                  v-model:value="formState.age"
                  :min="1"
                  :max="120"
                />
              </a-form-item>
              <a-form-item label="邮箱">
                <a-input
                  v-model:value="formState.email"
                  placeholder="请输入邮箱"
                />
              </a-form-item>
              <a-form-item label="手机号">
                <a-input
                  v-model:value="formState.phone"
                  placeholder="请输入手机号"
                />
              </a-form-item>
              <a-form-item>
                <a-button type="primary" @click="saveBasicInfo"
                  >保存修改</a-button
                >
              </a-form-item>
            </a-form>
          </a-tab-pane>

          <!-- 密码修改 -->
          <a-tab-pane key="2" tab="修改密码">
            <a-form :model="passwordForm" layout="vertical">
              <a-form-item label="原密码">
                <a-input-password
                  v-model:value="passwordForm.oldPassword"
                  placeholder="请输入原密码"
                />
              </a-form-item>
              <a-form-item label="新密码">
                <a-input-password
                  v-model:value="passwordForm.newPassword"
                  placeholder="请输入新密码"
                />
              </a-form-item>
              <a-form-item label="确认密码">
                <a-input-password
                  v-model:value="passwordForm.confirmPassword"
                  placeholder="请再次输入新密码"
                />
              </a-form-item>
              <a-form-item>
                <a-button type="primary" @click="changePassword"
                  >修改密码</a-button
                >
              </a-form-item>
            </a-form>
          </a-tab-pane>
        </a-tabs>
      </div>
    </div>
  </a-modal>
</template>

<script lang="ts" setup>
import { ref, reactive, defineProps, defineEmits, watch } from "vue";
import { message } from "ant-design-vue";
import { useAuthStore } from "@/store/auth";
import { CameraOutlined } from "@ant-design/icons-vue";
import { updateUserInfo, uploadAvatar, updatePassword } from "@/api/user";

interface UserInfo {
  username: string;
  nickname: string;
  avatar: string;
  email: string;
  phone: string;
  age: number;
}

const props = defineProps<{
  visible: boolean;
  userInfo: UserInfo | null;
}>();

const emit = defineEmits<{
  (e: "update:visible", visible: boolean): void;
  (e: "refresh"): void;
}>();

const fileInput = ref<HTMLInputElement | null>(null);
const previewAvatar = ref<string>("");
const authStore = useAuthStore();
// 基本信息表单
const formState = reactive({
  id: authStore.user?.id,
  username: authStore.user?.username,
  nickname: props.userInfo?.nickname || "",
  age: props.userInfo?.age || 0,
  email: props.userInfo?.email || "",
  phone: props.userInfo?.phone || "",
});

// 密码表单
const passwordForm = reactive({
  oldPassword: "",
  newPassword: "",
  confirmPassword: "",
});

// 监听 userInfo 变化，更新表单数据
watch(
  () => props.userInfo,
  (newUserInfo) => {
    if (newUserInfo) {
      formState.nickname = newUserInfo.nickname;
      formState.age = newUserInfo.age;
      formState.email = newUserInfo.email;
      formState.phone = newUserInfo.phone;
    }
  },
  { immediate: true } // 立即执行一次
);

// 监听 visible 变化，重置密码表单
watch(
  () => props.visible,
  (newVisible) => {
    if (!newVisible) {
      passwordForm.oldPassword = "";
      passwordForm.newPassword = "";
      passwordForm.confirmPassword = "";
    }
  }
);

// 触发文件选择
const triggerUpload = () => {
  fileInput.value?.click();
};

// 处理头像更改
const handleAvatarChange = async (e: Event) => {
  const target = e.target as HTMLInputElement;
  const file = target.files?.[0];
  if (!file) return;

  // 预览
  const reader = new FileReader();
  reader.onload = (e) => {
    previewAvatar.value = e.target?.result as string;
  };
  reader.readAsDataURL(file);

  // 上传
  try {
    const formData = new FormData();
    formData.append("avatar", file);
    const response = await uploadAvatar(formData);
    if (response.data.code === 200) {
      // 更新 authStore 中的用户信息
      const newAvatarUrl = response.data.data;
      authStore.updateUserAvatar(newAvatarUrl);
      message.success("头像更新成功");
      emit("refresh");
    }
  } catch (error) {
    message.error("头像上传失败");
  }
};

// 保存基本信息
const saveBasicInfo = async () => {
  try {
    const response = await updateUserInfo(formState);
    if (response.data.code === 200) {
      message.success("信息更新成功");
      emit("refresh");
    }
  } catch (error) {
    message.error("信息更新失败");
  }
};

// 修改密码
const changePassword = async () => {
  if (!authStore.user) {
    message.error("用户信息不存在");
    return;
  }

  if (passwordForm.newPassword !== passwordForm.confirmPassword) {
    message.error("两次输入的密码不一致");
    return;
  }

  try {
    const response = await updatePassword({
      userId: authStore.user?.id,
      oldPassword: passwordForm.oldPassword,
      newPassword: passwordForm.newPassword,
    });
    if (response.data.code === 200) {
      message.success("密码修改成功");
      passwordForm.oldPassword = "";
      passwordForm.newPassword = "";
      passwordForm.confirmPassword = "";
    }
  } catch (error) {
    message.error("密码修改失败");
  }
};

const handleCancel = () => {
  emit("update:visible", false);
};
</script>

<style scoped>
.settings-modal :deep(.ant-modal-content) {
  border-radius: 12px;
  overflow: hidden;
}

.settings-container {
  display: flex;
  gap: 32px;
}

.avatar-section {
  flex: 0 0 200px;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 24px;
  background: #fafafa;
  border-radius: 12px;
}

.avatar-wrapper {
  position: relative;
  margin-bottom: 20px;
  cursor: pointer;
}

.avatar-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  border-radius: 50%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  color: white;
  opacity: 0;
  transition: opacity 0.3s;
}

.avatar-wrapper:hover .avatar-overlay {
  opacity: 1;
}

.avatar-overlay .anticon {
  font-size: 24px;
  margin-bottom: 8px;
}

.info-section {
  flex: 1;
  padding: 24px;
  background: #fafafa;
  border-radius: 12px;
}

.upload-btn {
  width: 100%;
  margin-top: 16px;
}

:deep(.ant-tabs-nav) {
  margin-bottom: 24px;
}

:deep(.ant-form-item:last-child) {
  margin-bottom: 0;
}

:deep(.ant-input-number) {
  width: 100%;
}
</style>
